#!/usr/bin/env python
#
# GUI for installer automatic Tryton Application
#
import os
import Tkinter as tk
import ttk
import version
from installer import Installer
import threading

script_dir = os.path.dirname(__file__)

path_share = os.path.join(script_dir, '..', "share")
path_share_logo = os.path.join(path_share, 'presik.png')
file_logo = os.path.abspath(path_share_logo)



class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.parent = master
        self.createWidgets()
        self.parent["borderwidth"] = 10
        self.parent.title("Presik Technologies | Tryton Installer ")
        self.centerWindow()
        self.parent.resizable(False, False)
        self.pack(fill=tk.BOTH, expand=1)
        self.bytes = 0
        self.maxbytes = 0

    def createWidgets(self):
        frame = tk.Frame(self, borderwidth=1, bg="white")
        frame.pack(fill=tk.BOTH, expand=1)

        self.logo = tk.PhotoImage(file=file_logo)
        self.label_logo = tk.Label(frame, image=self.logo, bg="white")
        self.label_logo.pack(side=tk.TOP, fill=tk.BOTH, expand="yes")
        self.label_logo["borderwidth"] = 3

        self.title = tk.Label(
                frame,
                text="--- Instalador Tryton %s ---" % version.version,
                font=("Ubuntu Condensed", 14),
                bg="white",
                )
        self.title.pack(side=tk.TOP)
        self.title["borderwidth"] = 5

        self.ask = tk.Label(
                frame,
                text="Elija el tipo de instalacion ?",
                font=("Ubuntu Condensed", 12),
                anchor="w",
                bg="white",
                )
        self.ask['padx'] = 30
        self.ask.pack(side=tk.LEFT)
        self.ask["borderwidth"] = 5

        frame_buttons = tk.Frame(self, borderwidth=1, bg="white")
        frame_buttons.pack(fill=tk.BOTH, expand=1)
        self.button_standard = tk.Button(frame_buttons)
        self.button_standard["text"] = "Estandar"
        self.button_standard["command"] = self.action_standard
        self.button_standard["padx"] = 25
        self.button_standard.pack(side=tk.RIGHT, padx=5, pady=5)

        self.button_advanced = tk.Button(frame_buttons)
        self.button_advanced["text"] = "Avanzada"
        self.button_advanced["command"] = self.action_advanced
        self.button_advanced["padx"] = 25
        self.button_advanced.pack(side=tk.RIGHT, padx=5, pady=5)

        self.button_quit = tk.Button(frame_buttons, text="Salir", fg="red",
            command=self.parent.destroy)
        self.button_quit.pack(side=tk.RIGHT, padx=5, pady=5)
        self.button_quit["padx"] = 25

        self.label_info = tk.Label(
                self,
                text="",
                font=("Ubuntu Condensed", 11),
                width=40,
                )
        self.label_info['padx'] = 10
        self.label_info.pack()

        self.label_rate = tk.Label(
                self,
                text="0%",
                font=("Ubuntu Condensed", 11),
                anchor="w",
                width=5,
                )
        self.label_rate['padx'] = 10
        self.label_rate.pack()

        frame_bar = tk.Frame(self, borderwidth=1)
        frame_bar.pack(fill=tk.BOTH, expand=1)
        
        self.progress = ttk.Progressbar(frame_bar, orient="horizontal", 
            length=400, mode="determinate")
        self.progress.pack()

    def centerWindow(self):
        w = 410
        h = 310
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def action_standard(self):
        print("escogio estandar!")
        self.button_standard['state'] = tk.DISABLED
        self.button_advanced['state'] = tk.DISABLED
        self.button_quit['state'] = tk.DISABLED

        self.progress["value"] = 0
        self.installer = Installer(mode='d')
        target = threading.Thread(target=self._install)
        target.start()

    def _install(self):
        self.label_info['text'] = 'Instalando dependencias...'
        self.installer.install_prerequisites('d')
        self.label_info['text'] = 'Creando Virtual Env...'
        self.installer.create_virtualenv()
        self.label_info['text'] = 'Instalando modulos fuente...'
        self.installer.action_install_modules('p')
        self.label_info['text'] = 'Agregando script al arranque...'
        self.installer.add_script_init()
        self.label_info['text'] = 'Instalando modulos especiales...'
        self.installer.install_presik_modules()
        self.label_info['text'] = 'Configurando la base de datos...'
        self.installer.create_dbuser()
        #self.label_info['text'] = 'Creando acceso directo...'
        #install.create_shortcut()

    def set_maximum(self, value):
        self.progress["maximum"] = value

    def action_advanced(self):
        print("escogio avanzada!")

    def update_bytes(self, value):
        '''simulate reading 500 bytes; update progress bar'''
        self.bytes += value
        self.progress["value"] = self.bytes
        value =  "%s%%" % int(float(self.bytes) / float(self.progress["maximum"]) * 100)
        self.label_rate['text'] = value

        if self.bytes >= self.maxbytes:
            self.button_quit['state'] = tk.NORMAL
            self.label_info['text'] = 'Instalacion Exitosa...!'

if __name__ == "__main__":
    root = tk.Tk()
    app = Application(master=root)
    app.mainloop()
